<template>
  <div class="app-container">
    <el-card>
      <el-steps :active="stepActive" simple finish-status="success">
        <el-step title="1 编辑基本信息" />
        <el-step title="2 编辑商品详情" />
      </el-steps>
      <el-form ref="elForm" :model="formData" :rules="rules" label-width="110px">
        <div v-show="stepActive === 1">
          <el-form-item label-width="0" v-if="!$route.query.id">
            <SelectGoods v-model="selectGoodsId" />
          </el-form-item>
          <title-line title="基本信息" />

          <el-row>
            <el-col :lg="14" :xl="10">
              <el-form-item label="商品名称：" prop="name">
                <el-input
                  v-model="formData.name"
                  :maxlength="50"
                  placeholder="请输入商品名称50字以内"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="商品相册：" prop="images">
            <upload-image
              :isShowTip="true"
              :lazy="true"
              :file-type="['jpg', 'png', 'jpeg']"
              file-pixel="800*800"
              :file-size="1"
              :limit="8"
              :multiple="true"
              v-model="formData.images"
            />
          </el-form-item>

          <el-row>
            <el-col :lg="14" :xl="10">
              <el-form-item label="商品视频：" prop="video">
                <UploadVideo
                  :isShowTip="true"
                  :lazy="true"
                  :file-size="50"
                  :file-type="['mp4']"
                  v-if="!formData.video"
                  v-model="formData.video"
                />
                <div class="video-box" v-else>
                  <VideoPlayer :sources-data="videoSource" />
                  <el-button class="delete-btn" type="text" @click="deleteVideo">删除</el-button>
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="商品品牌：" prop="brandId">
            <SelectBrand v-model="formData.brandId" />
          </el-form-item>

          <title-line title="价格库存" />

          <el-row>
            <el-col :lg="24" :xl="22">
              <SelectSku
                v-if="skuSelectList.length"
                ref="selectSku"
                :skuSelectList="skuSelectList"
              />
            </el-col>
          </el-row>

          <el-row class="mt-30">
            <el-col :lg="14" :xl="10">
              <el-form-item label="库存预警：" prop="stockWarningQuantity">
                <el-input
                  placeholder="请输入库存预警"
                  :maxlength="3"
                  v-model.number="formData.stockWarningQuantity"
                />
                <p class="ft-12" style="color: #999999">库存达到预警值系统会进行提醒</p>
              </el-form-item>

              <el-form-item label="商品编码：">
                <el-input placeholder="请输入商品编码" v-model="formData.code" />
              </el-form-item>

              <el-form-item label="虚拟销量" prop="virtualSalesQuantity">
                <el-input
                  :maxlength="4"
                  placeholder="请输入虚拟销量"
                  v-model.number="formData.virtualSalesQuantity"
                />
                <p class="ft-12" style="color: #999999">后台填充虚拟销售数据</p>
              </el-form-item>
            </el-col>
          </el-row>

          <title-line title="配送方式" />
          <el-form-item label="配送方式：" required>
            <el-radio-group v-model="formData.distributionMode">
              <el-radio v-for="(item, index) in SEND_STATUS" :key="index" :label="item.value">{{
                item.label
              }}</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="运费模板：" v-if="formData.distributionMode === 1">
            <SelectTemplate v-model="formData.expressTemplateId" />
          </el-form-item>

          <title-line title="其他信息" />
          <el-form-item label="推荐到列表：" required>
            <el-radio-group v-model="formData.isSortCategory">
              <el-radio v-for="(item, index) in RECOMMMEND" :key="index" :label="item.value">{{
                item.label
              }}</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-row>
            <el-col :lg="12" :xl="10">
              <el-form-item label="商品排序：" prop="sort">
                <el-input v-model="formData.sort" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item class="text-center">
            <el-button @click="resetForm">取消</el-button>
            <el-button type="primary" @click="submitNextPage">下一步</el-button>
          </el-form-item>
        </div>

        <div v-show="stepActive === 2">
          <el-form-item class="mt-30" label-width="0" prop="details">
            <Tinymce v-model="formData.details" />
          </el-form-item>
          <el-form-item class="text-center">
            <el-button @click="submitPrevPage">上一步</el-button>
            <el-button @click="submitForm" type="primary">确定</el-button>
          </el-form-item>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import _ from 'lodash'
import rules from './rules-mixin'
import { useGenerateUUID } from '@/hooks/index'

import { SEND_STATUS, RECOMMMEND } from '@/enum'
import SelectSku from './components/SelectSku'
import SelectGoods from './components/SelectGoods'
import SelectBrand from './components/SelectBrand'
import SelectTemplate from './components/SelectTemplate'
export default {
  name: 'AddGoods',
  components: {
    SelectSku,
    SelectBrand,
    SelectGoods,
    SelectTemplate
  },
  props: {},
  mixins: [rules],
  data() {
    return {
      // 懒人模式选择商品id
      selectGoodsId: '',
      // 当前填写步骤
      stepActive: 1,

      // 规格值列表
      skuSelectList: [],

      // 提交表单
      formData: {
        // 商品名称
        name: '',
        // 商品相册
        images: [],
        // 商品视频
        video: '',
        // 品牌id
        brandId: '',
        // 配送方式 [1: 快递配送, 2: 门店自提],可用值:1,2
        distributionMode: 1,
        // 快递模板id
        expressTemplateId: '',
        // 库存预警值
        stockWarningQuantity: '',
        // 商品编码
        code: '',
        // 虚拟销量
        virtualSalesQuantity: _.random(1, 1000),
        // 排序
        sort: 99,
        // 推荐到列表
        isSortCategory: false,
        // 商品详情
        details: '',
        // 商品规格明细
        skuList: [],
        // 商品规格关系
        specRelation: {}
      }
    }
  },
  computed: {
    // 配送方式
    SEND_STATUS() {
      return SEND_STATUS
    },
    // 推荐状态
    RECOMMMEND() {
      return RECOMMMEND
    },
    videoSource() {
      return [this.formData.video]
    }
  },
  watch: {
    // 配送方式更改
    'formData.distributionMode'(newValue) {
      if (newValue === 2) {
        this.formData.expressTemplateId = ''
      }
    },

    // 懒人模式选择商品模板
    selectGoodsId(newValue) {
      console.log(newValue)
      this.getGoodsInfo(newValue)
    }
  },
  async created() {
    // 获取规格值列表
    await this.getSpecList()
    // 获取商品详情
    this.getGoodsInfo()
  },
  methods: {
    // 获取规格值列表
    async getSpecList() {
      try {
        const {
          data: { records }
        } = await this.$http.goods.spec.page({ params: { pageNo: 1, pageSize: 10 } })
        this.skuSelectList = records
      } catch (error) {
        console.log('getSpecList', error)
      }
    },

    // 获取商品详情
    async getGoodsInfo(id) {
      if (!this.$route.query.id && !id) return
      console.log('skuSelectList', this.skuSelectList)
      try {
        const { data } = await this.$http.goods.newcomer.getInfoById({
          id: this.$route.query.id || id
        })
        // 规格下拉列表赋值
        this.$refs.selectSku.skuList = [
          {
            name: this.skuSelectList.find(el => el.id === data.specRelation.specOneId)?.name,
            id: useGenerateUUID(),
            item: data.specRelation.specOneValues.map(el => ({ value: el, id: useGenerateUUID() }))
          }
        ]
        if (data.specRelation.specTwoId && data.specRelation.specTwoValues.length) {
          this.$refs.selectSku.skuList.push({
            name: this.skuSelectList.find(el => el.id === data.specRelation.specTwoId)?.name,
            id: useGenerateUUID(),
            item: data.specRelation.specTwoValues.map(el => ({ value: el, id: useGenerateUUID() }))
          })
        }
        const specList = this.$lodash.cloneDeep(this.$refs.selectSku.skuList)
        // console.log(specList)
        // sku列表赋值
        this.$refs.selectSku.formData.skuList = data.skuList.map(el => {
          const specOne = specList[0].item.find(item => item.value === el.specOneValue)
          let specTow = null
          if (el.specTwoValue) {
            specTow = specList[1].item.find(item => item.value === el.specTwoValue)
          }
          const key = el.specTwoValue ? specOne.id + '_' + specTow.id : specOne.id
          const attrSet = [
            { label: specList[0].name, specItemId: specOne.id, value: specOne.value }
          ]
          if (el.specTwoValue) {
            specList[1].item.find(item => item.value === el.specTwoValue)
            attrSet.push({
              label: specList[1].name,
              specItemId: specTow.id,
              value: specTow.value
            })
          }
          const sku = {
            attrSet,
            key,
            ...el,
            price: Number(el.price)
          }
          if (id) {
            delete sku.id
            delete sku.code
          }
          return sku
        })
        this.$refs.selectSku.createTempMergeIndex()

        this.formData = this.$lodash.cloneDeep(data)
        if (id) {
          delete this.formData.id
          delete this.formData.code
        }
        // console.log(data)
        // console.log(this.formData)
      } catch (error) {
        console.log('getGoodsInfo', error)
      }
    },

    handleVideoResponse(response) {
      return response
    },
    uploadVideoChange() {
      if (this.formData.video) {
        this.$refs.elForm.validateField('video')
      }
    },
    deleteVideo() {
      this.formData.video = ''
    },

    // 上一步
    submitPrevPage() {
      this.stepActive = 1
    },
    // 下一步
    submitNextPage() {
      this.$refs['elForm'].validate(valid => {
        if (!valid) return
        let skuValid = true
        // 验证sku模块相关
        this.$refs.selectSku.skuList.forEach(el => {
          if (!el.name) {
            this.$message.error('请选择规格名称')
            skuValid = false
          }
          el.item.forEach(item => {
            if (!item.value) {
              this.$message.error('请输入规格值')
              skuValid = false
            }
          })
        })
        if (!skuValid) return
        // 参数整合
        this.$refs.selectSku.$refs.skuForm.validate(valid => {
          if (!valid) return
          this.stepActive = 2
        })
      })
    },

    resetForm() {
      this.$router.back(-1)
      this.$refs['elForm'].resetFields()
    },

    // 新增提交商品
    submitForm() {
      // 参数整合
      const params = this.$lodash.cloneDeep(this.formData)
      // sku参数处理
      params.skuList = this.$refs.selectSku.formData.skuList
      params.specRelation = {}
      params.specRelation.specOneId = this.$refs.selectSku.skuSelectList.find(
        el => el.name === this.$refs.selectSku.skuList[0].name
      ).id
      params.specRelation.specOneValues = this.$refs.selectSku.skuList[0].item.map(el => el.value)
      if (this.$refs.selectSku.skuList.length > 1) {
        params.specRelation.specTwoId = this.$refs.selectSku.skuSelectList.find(
          el => el.name === this.$refs.selectSku.skuList[1].name
        ).id
        params.specRelation.specTwoValues = this.$refs.selectSku.skuList[1].item.map(el => el.value)
      }
      // 是否编辑商品
      const id = this.$route.query.id
      // 请求api
      let api = 'save'
      if (id) {
        params.id = id
        params.specRelation.id = this.formData.specRelation.id
        api = 'edit'
      }
      if (this.selectGoodsId) delete params.specRelation.id

      // // 验证是否有库存（聚合为false）
      // if (params.type === 3 && this.supplyCode === 'JuHe') {
      //   params.verifyStock = false
      // } else {
      //   params.verifyStock = true
      // }

      // 发送网络请求
      this.$http.goods.newcomer[api](params)
        .then(res => {
          // console.log(res)
          if (res.status === 200) {
            const message = id ? '编辑成功' : '新增成功'
            this.$message.success(message)
            this.$router.back()
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          console.log(err)
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.video-box {
  position: relative;
}
.delete-btn {
  position: absolute;
  z-index: 9999;
  top: 20px;
  right: 20px;
  background: #fff;
  padding: 5px;
}
</style>
